//
//  TentacleView.swift
//  GesturePassword4Swift
//
//  Created by feiin on 14/11/22.
//  Copyright (c) 2014 year swiftmi. All rights reserved.
//
//  Edited by Glitter on 16/01/12.

import UIKit

protocol TentacleViewDelegate {
    
    
    // 重置手势密码   密码   次数 要求2次
    func resetPassword(_ result: String,times:Int) -> Bool
    // 验证手势密码
    func verification(_ result: String) -> Bool
    
    func gestureTouchBegin()
    func gestureSetFail()
}
 
enum SetStyle {
    case set,verify   // 设置密码，校验密码
}

class TentacleView: UIView {

    var buttonArray: [GesturePasswordButton] = []
    var touchesArray: [[String: Float]] = []
    var touchedArray: [String] = []

    var lineStartPoint: CGPoint?
    var lineEndPoint: CGPoint?

    var delegate: TentacleViewDelegate?
   
     var  times  = 1 // 次数，设置需要输入两次
    var styleX: SetStyle?

   private var success: Bool = false
    private  var drawed: Bool = false

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor.clear
        isUserInteractionEnabled = true
        success = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        var touchPoint: CGPoint
        let touch: UITouch? = touches.first!

        touchesArray.removeAll()
        touchedArray.removeAll()

        delegate!.gestureTouchBegin()

        success = true
        drawed = false

        if touch != nil {

            touchPoint = touch!.location(in: self)

            for i in 0..<buttonArray.count {

                let buttonTemp = buttonArray[i]
                buttonTemp.success = true
                buttonTemp.selected = false

                if buttonTemp.frame.contains(touchPoint) {
                    let frameTemp = buttonTemp.frame
                    let point = CGPoint(x: frameTemp.origin.x+frameTemp.size.width/2, y: frameTemp.origin.y+frameTemp.size.height/2)

                    var dict: [String: Float] = [:]
                    dict["x"] = Float(point.x)
                    dict["y"] = Float(point.y)
                    //dict["num"] = Float(i)

                    touchesArray.append(dict)
                    lineStartPoint = touchPoint

                }
                buttonTemp.setNeedsDisplay()
            }
            setNeedsDisplay()
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        var touchPoint: CGPoint
        let touch: UITouch? = touches.first!

        if touch != nil {

            touchPoint = touch!.location(in: self)
            for i in 0..<buttonArray.count {

                let buttonTemp = buttonArray[i]

                if buttonTemp.frame.contains(touchPoint) {

                    let tps = touchedArray.filter { el in el == "num\(i)" }

                    if tps.count > 0 {
                        lineEndPoint = touchPoint
                        setNeedsDisplay()
                        return
                    }
                    touchedArray.append("num\(i)")
                    buttonTemp.selected = true
                    buttonTemp.setNeedsDisplay()

                    let frameTemp = buttonTemp.frame
                    let point = CGPoint(x: frameTemp.origin.x + frameTemp.size.width / 2, y: frameTemp.origin.y + frameTemp.size.height / 2)
                    var dict = [String: Float]()
                    dict["x"] = Float(point.x)
                    dict["y"] = Float(point.y)
                    dict["num"] = Float(i)

                    touchesArray.append(dict)

                    break
                }
            }

            lineEndPoint = touchPoint
            setNeedsDisplay()
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        var resultString: String = ""
 
        guard touchedArray.count > 3  else {
            KSToast("最少需要4个点")
      
            success = true
            drawed = false
            setNeedsDisplay()
            self.delegate!.gestureSetFail()
            return
        }
       
        
        
        for p in touchesArray {
            if p["num"] == nil {
                continue
            }
            let num = Int(p["num"]!)
            resultString += "\(num)"
        }
        drawed = true
        if styleX == .verify {
            success = delegate!.verification(resultString)
        } else {
            if times == 1 {
                success = delegate!.resetPassword(resultString,times:1)
                times += 1
                initView()
            } else {
                 success = delegate!.resetPassword(resultString,times:2)
            }
            
        }

        for i in 0..<touchesArray.count {

            if touchesArray[i]["num"] == nil {
                continue
            }

            let selection: Int = Int(touchesArray[i]["num"]!)
            let buttonTemp = buttonArray[selection]
            buttonTemp.success = success
            buttonTemp.setNeedsDisplay()
        }
        setNeedsDisplay()
     }

    @objc fileprivate func initView() {
        for but in buttonArray {
            but.selected = false
            success = true
            but.setNeedsDisplay()
        }
        touchesArray.removeAll()
        setNeedsDisplay()
    }

    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        // Drawing code

        if touchesArray.count <= 0 {
            return
        }

        for i in 0..<touchesArray.count {
            let context: CGContext = UIGraphicsGetCurrentContext()!

            if touchesArray[i]["num"] == nil {
                
            } else {
                if success {
                    context.setStrokeColor(UIColor(red: 2/255, green: 174/255, blue: 240/255, alpha: 0.7).cgColor)
                    // 线条颜色
                } else {
                    context.setStrokeColor(red: 208/255, green: 36/255, blue: 36/255, alpha: 0.7)
                    // 红色
                }

                context.setLineWidth(5)

                let x = CGFloat(touchesArray[i]["x"]!)
                let y = CGFloat(touchesArray[i]["y"]!)

                context.move(to: CGPoint(x: x, y: y))

                if i < touchesArray.count - 1 {
                    let x = CGFloat(touchesArray[i+1]["x"]!)
                    let y = CGFloat(touchesArray[i+1]["y"]!)
                    context.addLine(to: CGPoint(x: x, y: y))
                } else {

                    if success && drawed != true {
                        context.addLine(to: CGPoint(x: lineEndPoint!.x, y: lineEndPoint!.y))
                    }
                }
                context.strokePath()
            }

           
        }
    }

    func enterArgin() {

        touchesArray.removeAll()
        touchedArray.removeAll()

        for i in 0..<buttonArray.count {

            let buttonTemp = buttonArray[i]
            buttonTemp.success = true
            buttonTemp.selected = false
            buttonTemp.setNeedsDisplay()
        }
        setNeedsDisplay()
    }
}
